package com.zjzywl.smoke.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.repository.RoleRepository;
import com.zjzywl.smoke.service.AuthorityService;
import com.zjzywl.smoke.service.RoleService;
import com.zjzywl.smoke.util.RestResult;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.Authority;
import com.zjzywl.smoke.entity.Role;

@RestController
@RequestMapping(value = "/role")
public class RoleActionController extends BaseController {
	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private AuthorityService authorityService;

	@Autowired
	private RoleService roleService;

	// 获取角色列表
	@RequestMapping(value = "/list")
	public ResponseEntity<List<Role>> sysUserList(Model model) {
		List<Role> role = roleRepository.findAllByRemove();
		return RestResult.OK(role);
	}

	// 获取单个角色
	@RequestMapping(value = "/get/{roleId}")
	public ResponseEntity<Role> findRole(@PathVariable("roleId") Integer roleId) {
		Role findOne = roleRepository.findOne(roleId);
		return RestResult.OK(findOne);
	}

	// 创建角色
	@RequestMapping(value = "/save/{roleName}")
	public ResponseEntity<Role> findRole(@RequestBody Authority authority, @PathVariable("roleName") String roleName) {
		Role findByRoleName2 = roleService.findByRoleName(roleName);
		if (findByRoleName2 != null) {
			return RestResult.OK("角色名称已存在");
		}
		Role role = new Role();
		role.setName(roleName);
		roleService.save(role);

		Role findByRoleName = roleService.findByRoleName(roleName);
		if (findByRoleName != null) {
			authority.setRole(role);
			authorityService.save(authority);
		}
		return RestResult.OK(role);
	}

	// 修改角色信息
	@RequestMapping(value = "/update/{roleName}/{roleId}")
	public ResponseEntity<Role> updateRole(@RequestBody Authority authority, @PathVariable("roleName") String roleName,
			@PathVariable("roleId") String roleId) {
		Role role = roleService.findOne(Integer.parseInt(roleId));
		role.setName(roleName);
		roleService.save(role);

		Authority findByRoleId = authorityService.findByRoleId(Integer.parseInt(roleId));
		authority.setRole(role);
		authority.setAuId(findByRoleId.getAuId());
		authorityService.save(authority);

		return RestResult.OK(role);
	}

	// 删除角色信息
	@PostMapping(value = "/delect/{roleId}")
	public void delectRole(@PathVariable("roleId") int roleId) {
		roleService.delete(roleId);
	}

}
